// routes.go
package routes

import (
	"bsm/controllers"
	"bsm/daos"
	"bsm/logger"
	"bsm/middleware"
	"bsm/services"
	"os"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/jmoiron/sqlx"
)

func RegisterRoutes(r *gin.Engine, dbBSD *sqlx.DB, dbSCM *sqlx.DB) {

	// 创建Redis会话服务
	redisSessionService := services.NewRedisSessionService()

	// 清理过期会话
	if redisSessionService != nil {
		err := redisSessionService.CleanupExpiredSessions()
		if err != nil {
			logger.WithFields(map[string]interface{}{
				"layer":     "routes",
				"operation": "RegisterRoutes",
				"error":     err.Error(),
			}).Error("清理过期会话失败")
		}
	}

	// 启动自动会话清理（每小时一次）
	if redisSessionService != nil {
		redisSessionService.StartAutoCleanup(1 * time.Hour)
	}

	// 创建DAO
	daoUser := daos.NewUserDao(dbBSD)
	daoPms := daos.NewPmsDao(dbBSD)
	daoDesign := daos.NewDesignDao(dbBSD)
	daoScm := daos.NewScmDao(dbSCM)
	daoImport := daos.NewImportDao(dbBSD)
	daoExport := daos.NewExportDao(dbBSD)

	// 创建服务
	//svcRole := services.NewRoleService(daoUser, daoDesign) // 新增角色服务
	svcUser := services.NewUserService(daoUser) // 新增用户服务
	svcDifference := services.NewDifferenceService(daoPms)
	svcDesign := services.NewDesignService(daoDesign, daoUser, daoScm)
	svcImport := services.NewImportService(daoImport, daoUser)
	svcExport := services.NewExportService(daoExport, daoUser)
	svcConvert := services.NewConvertService()
	svcAuth := services.NewAuthService(daoUser)
	svcSystem := services.NewSystemService(daoUser, daoDesign, redisSessionService)

	// 初始化GIN-JWT中间件
	authMiddleware, err := middleware.InitAuthMiddleware(svcAuth, redisSessionService)
	if err != nil {
		logger.WithFields(map[string]interface{}{
			"layer":     "routes",
			"operation": "RegisterRoutes",
			"error":     err.Error(),
		}).Error("初始化JWT中间件失败")
		os.Exit(1)
	}

	// 创建控制器
	authController := controllers.NewAuthController(authMiddleware, redisSessionService)
	//roleController := controllers.NewRoleController(svcRole) // 新增角色控制器
	userController := controllers.NewUserController(svcUser) // 新增用户控制器
	pmsController := controllers.NewPmsController(svcDifference, svcAuth)
	designController := controllers.NewDesignController(svcDesign, svcImport, svcExport, svcAuth)
	multiLoginController := controllers.NewMultiLoginController(redisSessionService)
	systemController := controllers.NewSystemController(svcSystem, svcUser, svcAuth)
	importController := controllers.NewImportController(svcImport, svcAuth)
	exportController := controllers.NewExportController(svcExport, svcConvert, svcAuth)

	// 设置静态文件目录
	r.Static("/templates", "./frontend/static/templates")
	r.Static("/js", "./frontend/static/js")
	r.Static("/common", "./frontend/static/templates/common")
	r.Static("/uploads", "./uploads")
	r.Static("/css", "./frontend/static/css")
	r.Static("/layui", "./frontend/static/layui")

	// 设置默认路由指向 login.html
	r.GET("/", func(c *gin.Context) {
		c.File("./frontend/login.html")
	})

	// 设置主页面路由指向 index.html
	r.GET("/main", func(c *gin.Context) {
		c.File("./frontend/index.html")
	})

	// 单独为help.html添加路由
	r.StaticFile("/help.html", "./frontend/help.html")

	pms := r.Group("/pms")
	{
		// 使用authMiddleware的直接方法
		pms.POST("/login", authMiddleware.LoginHandler)
		pms.POST("/logout", authMiddleware.MiddlewareFunc(), authMiddleware.LogoutHandler)
		pms.GET("/refresh_token", authMiddleware.RefreshHandler)
		pms.GET("/validate-token", authMiddleware.MiddlewareFunc(), authController.ValidateToken)

		// 需要认证的路由组
		authRoot := pms.Group("/")
		authRoot.Use(authMiddleware.MiddlewareFunc())
		{
			// 用户个人中心路由
			user := authRoot.Group("/user")
			{
				user.GET("/profile", userController.GetProfile)
				user.POST("/change-password", userController.ChangePassword)
			}

			// 会话管理接口
			sessions := authRoot.Group("/sessions")
			{
				sessions.GET("", multiLoginController.GetSessions)
				sessions.POST("/terminate", multiLoginController.TerminateSession)
				sessions.POST("/terminate-others", multiLoginController.TerminateOtherSessions)
			}

			statistics := authRoot.Group("/statistics")
			{
				statistics.GET("/project/diff", pmsController.GetProjectDiff)
				statistics.GET("/project/diff/detail", pmsController.GetProjectDiffDetail)
			}

			design := authRoot.Group("/design")
			{
				design.POST("/CheckUserRole", userController.CheckUserRole)
				design.GET("/GetOrgList", designController.GetOrgList)
				design.GET("/GetNormLabor", designController.GetNormLabor)
				design.GET("/GetNormConversion", designController.GetNormConversion)
				design.GET("/GetNormMaterial", designController.GetNormMaterial)
				design.POST("/GetMaterialPrice", designController.GetMaterialPrice)
				design.GET("/GetProjectReviewer", designController.GetProjectReviewer)
				design.POST("/CreateProject", designController.CreateProjectBudget)
				design.POST("/CreateFrom", designController.CreateProjectBudgetFrom)
				design.GET("/GetProjectBase", designController.GetProjectBase)
				design.POST("/UpdateProjectBase", designController.UpdateProjectBase)
				design.GET("/GetProjectResume", designController.GetProjectResume)
				design.GET("/ProjectList", designController.GetProjectList)
				design.GET("/LoadLabor", designController.LoadProjectLabor)
				design.GET("/LoadMaterial", designController.LoadProjectMaterial)
				design.GET("/LoadOtherFee", designController.LoadProjectOtherFee)
				design.POST("/SaveLabor", designController.SaveProjectLabor)
				design.POST("/SaveMaterial", designController.SaveProjectMaterial)
				design.POST("/SaveOtherFee", designController.SaveProjectOtherFee)
				design.POST("/SaveTable", designController.SaveProject)
				design.POST("/ExportProject", exportController.Export)
				design.POST("/ImportProject", importController.Import)
				design.POST("/FileProject", designController.SetProjectFiled)
				design.POST("/GetProjectBalance", designController.GetProjectBalance)
				design.POST("/GetProjectOutbound", designController.GetProjectOutbound)

			}
		}
	}

	// 系统管理页面路由组
	adminPages := r.Group("/admin")
	adminPages.Use(authMiddleware.MiddlewareFunc())
	adminPages.Use(middleware.AdminRequired())
	{
		// 主管理框架
		adminPages.GET("", func(c *gin.Context) { c.File("./frontend/admin.html") })

		// 拆分后的管理页面
		adminPages.GET("/dashboard", func(c *gin.Context) { c.File("./frontend/admin/dashboard.html") })
		adminPages.GET("/user-management", func(c *gin.Context) { c.File("./frontend/admin/user-management.html") })
		adminPages.GET("/session-management", func(c *gin.Context) { c.File("./frontend/admin/session-management.html") })
		adminPages.GET("/project-management", func(c *gin.Context) { c.File("./frontend/admin/project-management.html") })
		adminPages.GET("/system-stats", func(c *gin.Context) { c.File("./frontend/admin/system-stats.html") })

		// 用户编辑弹窗
		adminPages.GET("/user-edit", func(c *gin.Context) { c.File("./frontend/admin/user-edit.html") })
		adminPages.GET("/addUser", func(c *gin.Context) { c.File("./frontend/admin/addUser.html") })
	}

	// 管理API组 - 需要先JWT认证，再管理员权限检查
	adminAPI := r.Group("/admin")
	adminAPI.Use(authMiddleware.MiddlewareFunc()) // 先JWT认证
	adminAPI.Use(middleware.AdminRequired())      // 再管理员权限检查
	{
		adminAPI.GET("/roles", systemController.GetRoles)
		adminAPI.GET("/generate-user-id", systemController.GenerateUserId)
		adminAPI.POST("/reset-password", systemController.ResetPassword)
		adminAPI.POST("/freeze-user", systemController.FreezeUser)
		adminAPI.POST("/unfreeze-user", systemController.UnfreezeUser)

		adminAPI.GET("/users", systemController.GetUsers)
		adminAPI.POST("/users", systemController.AddUser)
		adminAPI.GET("/sessions", systemController.GetSessions)
		adminAPI.GET("/projects", systemController.GetProjects)
		adminAPI.GET("/stats", systemController.GetSystemStats)
		adminAPI.DELETE("/sessions/:session_id", systemController.TerminateSession)
		adminAPI.DELETE("/users/:user_id/sessions", systemController.TerminateUserSessions)
		adminAPI.DELETE("/projects/:design_code", designController.DeleteProject)
	}

	// 添加健康检查端点
	r.GET("/health", func(c *gin.Context) {
		c.JSON(200, gin.H{"status": "ok"})
	})
}
